﻿(function(ko, datacontext) {
    datacontext.book = book;
    datacontext.bookList = bookList;
    
    function book(data) {
        var self = this;
        data = data || {};

        self.bookId = data.bookId;
        self.title = data.title;
        self.author = data.author;
        self.description = data.description;
        self.isRead = data.isRead;
        self.rating = data.rating;
        self.dateRead = data.dateRead;
        self.creator = data.creator;
        self.bookListId = data.bookListId;

        self.errorMessage = ko.observable();

        saveChanges = function () {
            //TODO check if current user id == creator
            return datacontext.saveChangedBook(self);
        };

        self.title.subscribe(saveChanges);
        self.author.subscribe(saveChanges);
        self.description.subscribe(saveChanges);
        self.isRead.subscribe(saveChanges);
        self.rating.subscribe(saveChanges);
        self.dateRead.subscribe(saveChanges);
        
        self.toJson = function() { return ko.toJSON(self); };

    };
    
    function bookList(data) {
        var self = this;
        data = data || {};

        self.bookListId = data.bookListId;
        self.userId = data.userId;
        self.books = ko.observableArray(importBooks(data.books));

        self.isEditingBook = ko.observable(false);

        self.removeBook = function() {
            //TODO remove book from list and persist list
        };

        self.books.subscribe(function() {
            return datacontext.saveChangedBookList(self);
        });

        self.toJson = function() { return ko.toJSON(self); };

    }
    
    function importBooks(books) {
        return $.map(books || [], function(bookData) {
            return datacontext.createBook(bookData);
        });
    }

    bookList.prototype.addBook = function() {
        
    };

})(ko, netbooksApp.datacontext);